<script setup lang="js">
import { computed, onMounted, reactive, ref, toRaw, watch } from 'vue'
// import { ElMessage, ElNotification } from 'element-plus'
// 组件状态管理
const testStatus = ref('') // 'success', 'error', or ''
const testMessage = ref('')
const isLoading = ref(false)

// 目录扫描相关状态
const directoryPath = ref('')
const isScanning = ref(false)
const scanProgress = ref(0)
const scanStatus = ref('')
const scanErrors = ref([])
const resources = ref([])
// 资源扫描相关状态
const resourcePort = ref('8080') // 默认资源端口
const resourceBaseUrl = computed(() => {
  // 使用数据库配置中的host + 用户输入的端口
  return `http://${dbConfig.host}:${resourcePort.value}`
})

// 新增上传进度状态
const uploadProgress = ref(0)

// 添加保存状态
const isSaving = ref(false)
const saveStatus = ref('') // 'success', 'error'
const saveMessage = ref('')

// 数据库配置 (响应式对象)
const dbConfig = reactive({
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: '123456',
  database: 'xzs'
})

// 添加结果状态对象
const resultInfo = reactive({
  scan: {
    total: 0,
    errors: 0,
    messages: []
  },
  upload: {
    total: 0,
    success: 0,
    errors: 0,
    messages: []
  }
})

// 检查是否在Electron环境中
const isElectron = ref(false)

onMounted(() => {
  // 检查是否存在 electron 对象
  isElectron.value = !!window.electron?.ipcRenderer
  if (!isElectron.value) {
    testStatus.value = 'error'
    testMessage.value = '当前不在Electron环境中运行'
  }

  // 新增上传进度监听
  if (isElectron.value) {
    window.electron.ipcRenderer.on('upload-progress', (event, progress) => {
      uploadProgress.value = progress
    })
  }
}) // 测试连接
// 测试数据库连接
const testConnection = async () => {
  if (!isElectron.value) return

  isLoading.value = true
  testStatus.value = ''
  testMessage.value = ''

  try {
    const dbConfigCopy = toRaw(dbConfig)
    // 调用主进程初始化数据库
    const result = await window.electron.ipcRenderer.invoke(
      'resource:initializeDatabase',
      dbConfigCopy
    )

    if (result.success) {
      testStatus.value = 'success'
      testMessage.value = '数据库连接成功！'
    } else {
      testStatus.value = 'error'
      testMessage.value = result.message
      testMessage.value = '连接失败！'
    }
  } catch (error) {
    testStatus.value = 'error'
    console.error(error.message)
    //testMessage.value = '连接失败: ' + error.message
    testMessage.value = '连接失败！'
  } finally {
    isLoading.value = false
  }
}

// 分页控制
const currentPage = ref(1)
const pageSize = ref(10)

// 计算分页数据
const paginatedResources = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return resources.value.slice(start, end)
})

// 打开目录选择对话框
const openDirectory = async () => {
  try {
    const result = await window.electron.ipcRenderer.invoke('dialog:openDirectory')
    if (!result.canceled && result.filePaths.length > 0) {
      directoryPath.value = result.filePaths[0]
    }
  } catch (error) {
    console.error('打开目录失败:', error)
    // 显示错误提示
  }
}

// 扫描目录并生成资源数据
const scanDirectory = async () => {
  resultInfo.scan.total = 0
  resultInfo.scan.errors = 0
  resultInfo.scan.messages = []
  if (!directoryPath.value) {
    // 提示选择目录
    return
  }

  isScanning.value = true
  scanProgress.value = 0
  scanStatus.value = ''
  scanErrors.value = []
  resources.value = []

  try {
    const result = await window.electron.ipcRenderer.invoke(
      'resource:scanDirectory',
      directoryPath.value,
      resourceBaseUrl.value
    )

    resources.value = result.resources || []
    scanErrors.value = result.errors || []

    // 更新扫描结果
    resultInfo.scan.total = resources.value.length
    resultInfo.scan.errors = scanErrors.value.length
    resultInfo.scan.messages = [...scanErrors.value]

    scanStatus.value = scanErrors.value.length > 0 ? 'exception' : 'success'
    scanProgress.value = 100
  } catch (error) {
    console.error('扫描失败:', error)
    scanStatus.value = 'exception'
    scanErrors.value.push(`扫描失败: ${error.message}`)
    // 更新扫描结果
    resultInfo.scan.total = 0
    resultInfo.scan.errors = 1
    resultInfo.scan.messages = [`扫描失败: ${error.message}`]
  } finally {
    isScanning.value = false
  }
}

// 保存资源到数据库
const saveResources = async () => {
  resultInfo.upload.total = 0
  resultInfo.upload.success = 0
  resultInfo.upload.errors = 0
  resultInfo.upload.messages = []
  if (resources.value.length === 0) {
    // ElMessage.warning('没有可保存的资源数据')
    return
  }

  isSaving.value = true
  saveStatus.value = ''
  saveMessage.value = ''
  uploadProgress.value = 0 // 重置进度

  try {
    // 使用结构化克隆
    //const payload = structuredClone(resources.value)
    const payload = JSON.parse(JSON.stringify(toRaw(resources.value)))
    const result = await window.electron.ipcRenderer.invoke('resource:saveResources', payload)

    if (result.success) {
      saveStatus.value = 'success'
      saveMessage.value = `成功保存 ${result.count} 条资源数据!`
      // ElMessage({ message: saveMessage, type: 'success' })
      uploadProgress.value = 100
      // 更新上传结果
      resultInfo.upload.total = result.count || 0
      resultInfo.upload.success = result.count || 0
      resultInfo.upload.errors = result.errors?.length || 0
      resultInfo.upload.messages = result.errors || []
    } else {
      // 更新上传结果
      resultInfo.upload.total = resources.value.length
      resultInfo.upload.success = result.count || 0
      resultInfo.upload.errors = result.errors?.length || 1
      resultInfo.upload.messages = result.errors || [result.message || '未知错误']

      saveStatus.value = 'error'
      saveMessage.value = result.message || '保存资源失败'
      // ElMessage.error(saveMessage.value)

      // 显示详细错误
      // if (result.errors && result.errors.length > 0) {
      //   result.errors.forEach((error) => {
      //     ElNotification.error({
      //       title: '保存错误',
      //       message: error,
      //       duration: 5000
      //     })
      //   })
      // }
    }
  } catch (error) {
    // 更新上传结果
    resultInfo.upload.total = resources.value.length
    resultInfo.upload.success = 0
    resultInfo.upload.errors = 1
    resultInfo.upload.messages = [`保存失败: ${error.message}`]
    saveStatus.value = 'error'
    saveMessage.value = `保存失败: ${error.message}`
    console.error('保存失败:', error)
    // ElMessage.error(saveMessage.value)
  } finally {
    isSaving.value = false
  }
}

// 分页切换
const handlePageChange = (page) => {
  currentPage.value = page
}

// 监听数据库配置变化，重置资源相关状态
watch(
  () => dbConfig.host,
  () => {
    resources.value = []
    scanErrors.value = []
  }
)
</script>

<template>
  <el-tabs type="card" class="m-5">
    <el-tab-pane label="数据库连接">
      <div class="flex flex-1 flex-col justify-center items-center m-5">
        <div class="fr-m1">
          <div class="fr-gap2-m1">
            <span class="w-30">主机：</span>
            <el-input
              v-model="dbConfig.host"
              class="w-100"
              placeholder="请输入数据库链接地址"
            ></el-input>
          </div>
          <div class="fr-gap2-m1">
            <span class="w-30">端口：</span>
            <el-input v-model="dbConfig.port" class="w-100" placeholder="默认3306"></el-input>
          </div>
        </div>
        <div class="fr-m1">
          <div class="fr-gap2-m1">
            <span class="w-30">用户名：</span>
            <el-input
              v-model="dbConfig.user"
              class="w-100"
              placeholder="请输入用户名默认root"
            ></el-input>
          </div>
          <div class="fr-gap2-m1">
            <span class="w-30">密码：</span>
            <el-input
              v-model="dbConfig.password"
              class="w-100"
              type="password"
              placeholder="请输入密码"
            ></el-input>
          </div>
        </div>
        <div class="fr-m1">
          <div class="flex flex-row gap-2 m-1">
            <div class="fr-gap2-m1">
              <span class="w-30">数据库名：</span>
              <el-input
                v-model="dbConfig.database"
                class="w-100"
                placeholder="请输入数据库名"
              ></el-input>
            </div>

            <div class="flex flex-row items-center w-69">
              <el-button :disabled="isLoading" size="small" type="danger" @click="testConnection"
                >测试连接</el-button
              >
              <span
                class="ml-5 mr-2 text-2xl text-green-400"
                :class="{
                  'success-icon': testStatus === 'success',
                  'error-icon': testStatus === 'error'
                }"
              >
                {{ testStatus === 'success' ? '✓' : '✗' }}
              </span>
              <span
                class="text-green-400 text-1.5xl"
                :class="{
                  success: testStatus === 'success',
                  error: testStatus === 'error'
                }"
                >{{ testMessage }}</span
              >
            </div>
          </div>
        </div>
      </div>
    </el-tab-pane>
    <el-tab-pane label="数据标注">
      <div class="flex flex-col m-5 items-center">
        <div class="fr-m1-w145">
          <el-input
            v-model="directoryPath"
            class="w-200 mx-2"
            placeholder="请选择文件所在目录"
          ></el-input>
          <el-button type="primary" @click="openDirectory">选择文件</el-button>
          <el-button type="primary" :disabled="isScanning" @click="scanDirectory"
            >扫描目录</el-button
          >
        </div>
        <div class="fr-m1-w145">
          <el-progress
            class="w-102 mx-2"
            :percentage="uploadProgress"
            :status="
              saveStatus === 'error' ? 'exception' : saveStatus === 'success' ? 'success' : ''
            "
            :show-text="false"
          />
          <div class="w-18 self-center">
            <el-input v-model="resourcePort" placeholder="端口号" />
          </div>
          <el-button
            class="ml-3"
            type="success"
            :disabled="isSaving || resources.length === 0"
            :loading="isSaving"
            @click="saveResources"
          >
            {{ isSaving ? `上传中 (${uploadProgress}%)` : '开始上传' }}
          </el-button>
        </div>
      </div>

      <!-- 统一结果提示框 -->
      <div class="result-container">
        <!-- 扫描结果 -->
        <el-alert
          v-if="resultInfo.scan.total > 0 || resultInfo.scan.errors > 0"
          :type="resultInfo.scan.errors > 0 ? 'error' : 'success'"
          :title="`扫描结果: 发现 ${resultInfo.scan.total} 个资源，有 ${resultInfo.scan.errors} 个错误`"
          show-icon
          auto-close="1000"
          class="mb-4"
        >
          <!--          <div-->
          <!--            v-for="(msg, idx) in resultInfo.scan.messages"-->
          <!--            :key="'scan-' + idx"-->
          <!--            class="error-message"-->
          <!--          >-->
          <!--            {{ msg }}-->
          <!--          </div>-->
        </el-alert>

        <!-- 上传结果 -->
        <el-alert
          v-if="resultInfo.upload.total > 0"
          :type="resultInfo.upload.errors > 0 ? 'error' : 'success'"
          :title="`上传结果: ${resultInfo.upload.success} 个成功，${resultInfo.upload.errors} 个失败`"
          show-icon
          class="mb-4"
          :closable="true"
        >
          <!--                    <div-->
          <!--                      v-for="(msg, idx) in resultInfo.upload.messages"-->
          <!--                      :key="'upload-' + idx"-->
          <!--                      class="error-message"-->
          <!--                    >-->
          <!--                      {{ msg }}-->
          <!--                    </div>-->
          <div v-if="resultInfo.upload.success > 0" class="success-message">
            资源已成功保存到数据库！
          </div>
        </el-alert>
      </div>
      <el-table :data="paginatedResources" border style="width: 100%">
        <el-table-column prop="title" label="标题" width="180" />
        <el-table-column prop="resourceType" label="类型" width="100" />
        <el-table-column prop="catalog" label="所属分类" />
        <el-table-column prop="fullUrl" label="完整URL" />
      </el-table>

      <el-pagination
        background
        layout="prev, pager, next"
        :total="resources.length"
        :page-size="pageSize"
        :current-page="currentPage"
        class="mt-4"
        @current-change="handlePageChange"
      />
    </el-tab-pane>
  </el-tabs>
</template>
